<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import LuckyExcel from 'luckyexcel'
import AnalyesAPI from "@/api/system/analyes";
import dayjs from "dayjs";
import {useAnalysetStore} from "@/store/index";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "row": 9,
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "湿样质量(g)",}, // B1
        {"r": 0, "c": 2, "v": "干燥后样品质量(g)",}, // B1
        {"r": 0, "c": 3, "v": ">10目筛的质量(g)",}, // B1
        {"r": 0, "c": 4, "v": "过10目筛的质量(g)",}, // B1
        {"r": 0, "c": 5, "v": "过筛目数/孔径（ ）",}, // B1
        {"r": 0, "c": 6, "v": "样品重量 (g)",}, // B1
        {"r": 0, "c": 7, "v": "检测项目  分析方法   浸提方法",}, // B1
        {"r": 0, "c": 8, "v": "备注",}, // B1
      ], // 初始化数据
      "config": {
        "merge": {}, // 合并单元格
        "columnlen": { // 设置列宽
          "0": 130, // 第一列宽度 150px
          "1": 130, // 第二列宽度 120px
          "2": 130, // 第三列宽度 180px
          "3": 130, // 第四列宽度 100px
          "4": 130, // 第五列宽度 200px
          "5": 130,  // 第六列宽度 150px
          "6": 130,  // 第六列宽度 150px
          "7": 200,  // 第六列宽度 150px
          "8": 130,  // 第六列宽度 150px
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};
const tableOption = ref([
  {table: '仪器名称', id: 1,}
])
const waterForm = ref({})
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const checkDialogVisible = ref(false)
const processedData = ref([])
const switchAB = ref(true)
const sheetData = ref('')
const jsonData = ref(null)
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  getWaterCapacity()
});

// 获取——获取 水质容量A   工作表
const getWaterCapacity = () => {
  AnalyesAPI.getAnalyseACapacity({id: analyseStatusPage.waterForm.id, record_sn: record_sn}).then(data => {
    console.log('获取水质容量 A单', data)
    waterForm.value = data
    sheetData.value = JSON.parse(data.configs)
    processedData.value = data.adatas
  })
}

const loadDataFromLocal = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  console.log(options.data)
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || null,
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  console.log(data);
  // 调用函数
  processedData.value = processData(data);

  // 调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    // record_sn: record_sn,
    record_sn: 83,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
  }).then(data => {
    console.log('调接口拿数据', data)
  })
};

const processData = (data) => {
  if (!data || data.length < 2) {
    return [];
  }

  // 提取表头
  const headers = data[0].map(item => item.field || "");

  // 提取数据行
  const values = data[1].map(item => item.value ?? null);

  // 构建结果
  const result = [];
  const rowObject = {};
  headers.forEach((header, index) => {
    if (header.trim()) {
      rowObject[header] = values[index] ?? null;
    }
  });

  result.push(rowObject);

  return result;
};

function formatLuckysheetData(sheetData) {
  const formattedData = [];

  // 假设第一行为标题行
  const headers = sheetData[0].cells.map(cell => cell.v);

  // 遍历每一行数据（从第二行开始）
  for (let i = 1; i < sheetData.length; i++) {
    const row = sheetData[i];
    const rowData = {};

    // 将每行的数据映射到对象属性
    row.cells.forEach((cell, index) => {
      rowData[headers[index]] = cell.v;
    });

    formattedData.push(rowData);
  }

  return formattedData;
}


// 用于获取最新的表格数据
const getUpdatedData = () => {
  checkDialogVisible.value = true
};
const handleCheckClose = () => {
  checkDialogVisible.value = false
}


// 确认提交校核
const handleSubmit = () => {
  console.log(checkTime.value)
  const formattedDate = checkTime.value ? dayjs(checkTime.value).format('YYYY-MM-DD') : '';
  console.log(analyseStatusPage.waterForm.id)
  AnalyesAPI.handleCheckTimeData({
    id: analyseStatusPage.waterForm.add_form_id,
    submit_date: formattedDate
  }).then(data => {
    if (data === 1) {
      ElMessage.success('提交成功！')
      checkDialogVisible.value = false
    }
  })
}

// 上传文件
const loadExcel = (evt) => {
  const files = evt.target.files
  console.log(files)
  if (files == null || files.length == 0) {
    alert('No files wait for import')
    return
  }
  let name = files[0].name
  let suffixArr = name.split('.'),
      suffix = suffixArr[suffixArr.length - 1]
  if (suffix != 'xlsx') {
    alert('Currently only supports the import of xlsx files')
    return
  }
  LuckyExcel.transformExcelToLucky(files[0], function (exportJson, luckysheetfile) {
    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
      alert('Failed to read the content of the excel file, currently does not support xls files!')
      return
    }
    console.log('exportJson', exportJson.sheets)
    jsonData.value = exportJson

    luckysheet.destroy()
    luckysheet.create({
      container: 'luckysheet', //luckysheet is the container id
      showinfobar: false,
      data: exportJson.sheets,
      title: exportJson.info.name,
      userInfo: exportJson.info.name.creator
    })
  })
}

const handleSwitch = () => {
  switchAB.value = !switchAB.value
}
</script>

<template>
  <div class="card">
    <el-card class="box-card">
      <h1 style="text-align: center">土壤、固体废物 样品制备原始记录</h1>
      <div>SXLPHJ/JL/CX-22-83</div>
      <table class="table">
        <tr>
          <td colspan="2" style="width: 10%;">任务编号</td>
          <td colspan="6" style="width: 7%;">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.task_name"/>
          </td>
          <td colspan="2" style="width: 7%;">采样日期</td>
          <td colspan="2" style="width: 7%;">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.sampling_time"/>
          </td>
          <td colspan="1" style="width: 7%;">制样日期</td>
          <td colspan="5">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.zyrq"/>
          </td>
        </tr>
        <tr>
          <td colspan="2" style="width: 10%;">样品类别</td>
          <td colspan="8">
            <el-checkbox-group v-model="waterForm.category_id">
              <el-checkbox label="土壤" value="土壤"/>
              <el-checkbox label="固体废物" value="固体废物"/>
              <el-checkbox label="其他" value="其他"/>
              <!--              <el-input v-if="waterForm.category_id.includes('其他')" v-model="waterForm.otherCategory"-->
              <!--                        placeholder="请输入其他类别"/>-->
            </el-checkbox-group>
          </td>
          <td colspan="2">装样容器</td>
          <td colspan="8">
            <el-checkbox-group v-model="waterForm.zycontainer">
              <el-checkbox label="样品袋" value="样品袋"/>
              <el-checkbox label="样品瓶" value="样品瓶"/>
              <el-checkbox label="其他" value="其他"/>
              <!--              <el-input v-if="waterForm.category_id.includes('其他')" v-model="waterForm.otherCategory"-->
              <!--                        placeholder="请输入其他类别"/>-->
            </el-checkbox-group>
          </td>
        </tr>
        <tr>
          <td colspan="2" rowspan="2">风干方式</td>
          <td colspan="2">
            <el-radio-group v-model="waterForm.fgtype">
              <el-radio label="自然风干" value="1"/>
            </el-radio-group>
          </td>
          <td colspan="2">设备名称</td>
          <td colspan="2">设备型号</td>
          <td colspan="2">设备编号</td>
          <td colspan="2" rowspan="2">
            <el-checkbox-group v-model="waterForm.zytype">
              <el-checkbox label="研磨方式" value="1"/>
              <el-checkbox label="破碎方式" value="1"/>
            </el-checkbox-group>
          </td>
          <td colspan="1" style="width: 7%;">
            <el-checkbox-group v-model="waterForm.type">
              <el-checkbox label="手工" value="1"/>
            </el-checkbox-group>
          </td>
          <td colspan="1" style="width: 7%;">仪器名称</td>
          <td colspan="2" style="width: 10%;">仪器型号</td>
          <td colspan="3">仪器编号</td>
        </tr>
        <tr>
          <td colspan="2">
            <el-radio-group v-model="waterForm.fgtype">
              <el-radio label="设备风干" value="2"/>
            </el-radio-group>
          </td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.fg_device_name"/>
          </td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.fg_device_model"/>
          </td>
          <td colspan="2">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.fg_device_number"/>
          </td>
          <td colspan="1" style="width: 7%;">
            <el-checkbox-group v-model="waterForm.type">
              <el-checkbox label="仪器" value="2"/>
            </el-checkbox-group>
          </td>
          <td colspan="1" style="width: 7%;">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.device_name"/>
          </td>
          <td colspan="2" style="width: 10%;">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.device_model"/>
          </td>
          <td colspan="3">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.device_number"/>
          </td>
        </tr>
      </table>
      <!--      <input id="uploadBtn" type="file" @change="loadExcel"/>-->
      <div id="luckysheet" style="width:100%;height:500px;"></div>
      <table class="table">
        <tr>
          <td style="width: 3%;">备注</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.notes"/>
          </td>
        </tr>
      </table>
    </el-card>


    <el-card class="box-card" style="margin-top: 30px">
      <div style="display: flex;justify-content: flex-end">
        <!-- <el-button @click="handleSwitch">
          {{ switchAB ? 'B面' : 'A面' }}
        </el-button> -->
        <div>
          <el-button>取消</el-button>
          <el-button>新增</el-button>
          <el-button>复制并新增</el-button>
          <el-button @click="loadDataFromLocal">保存</el-button>
          <el-button type="primary" @click="getUpdatedData">提交</el-button>
        </div>
      </div>
    </el-card>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse;
  /* 表格边框合并 */
  text-align: left;
  /* 默认左对齐 */
  font-size: 14px;
  /* 字体大小 */
  color: #606266;
  /* 默认字体颜色 */
  margin-bottom: 20px;
}

.table th,
.table td {
  border: 1px solid #c2bfbf;
  /* 表格单元格边框颜色 */
  padding: 12px;
  /* 单元格内边距 */
}

.table th {
  background: #f5f7fa;
  /* 表头背景色 */
  font-weight: 600;
  /* 表头字体加粗 */
  color: #303133;
  /* 表头字体颜色 */
  text-align: center;
  /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
}

::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
